package com.novacloud.utils;

import com.alibaba.fastjson.JSON;
import com.novacloud.dto.UserToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -3301605591108950415L;

    static final String CLAIM_KEY_USERNAME = "sub";
    static final String CLAIM_KEY_CREATED = "created";

    private String secret = "mySecret";

    private Long expiration = 604800L;

    public String getUsernameFromToken(String token) {
        String username;
        try {
            final Claims claims = getClaimsFromToken(token);
            UserToken user = claims.get(CLAIM_KEY_USERNAME, UserToken.class);
            username = user.getUserName();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public UserToken getUserFromToken(String token) {
        UserToken userToken;
        try {
            final Claims claims = getClaimsFromToken(token);
            userToken = JSON.parseObject(claims.getSubject(), UserToken.class);
        } catch (Exception e) {
            userToken = null;
        }
        return userToken;
    }

    public UserToken getUserFromToken(HttpHeaders headers) {
        UserToken userToken;
        try {
            String authorization = headers.getFirst("Authorization");
            final Claims claims = getClaimsFromToken(authorization);
            userToken = JSON.parseObject(claims.getSubject(), UserToken.class);
        } catch (Exception e) {
            userToken = null;
        }
        return userToken;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    public String generateToken(UserToken userToken) {
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put(CLAIM_KEY_USERNAME, JSON.toJSON(userToken).toString());
        // claims.put(CLAIM_KEY_AUDIENCE, generateAudience(device));
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }
}